package game.breeze.message.codec.mina;

import game.breeze.message.AppMessage;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.filter.codec.demux.MessageEncoder;

public class MinaMessageEncoder<T extends AppMessage> implements MessageEncoder<T> {

	@Override
	public void encode(IoSession session, T message, ProtocolEncoderOutput out) throws Exception {
		IoBuffer buffer = IoBuffer.allocate(message.getBuffer().available() + 8);
		buffer.setAutoExpand(true);
		buffer.putInt(message.getType());
		buffer.putInt(message.getBuffer().available());
		buffer.put(message.getBuffer().getBytes());
		buffer.flip();
		out.write(buffer);
	}
}
